import WxmpRsa from 'wxmp-rsa'
import RSA from "@/utils/wxapp_rsa.js"
import {
	publicKey,
	privateKey
} from "@/utils/secretKey";

export default {
	/**
	 * 加密
	 * @param {string} data
	 * @param {string} publicKey
	 * @returns {string}
	 */
	encrypt(data, publicKey) {
		return new Promise((resolve, reject) => {
			// 实例化rsa
			const rsa = new WxmpRsa();
			// 设置公钥
			rsa.setPrivateKey(publicKey);
			// 加密
			const cryptStr = rsa.encryptLong(JSON.stringify(data));
			console.log('加密后的结果：', cryptStr);
			// 加签
			let sign_rsa = new RSA.RSAKey();
			sign_rsa = RSA.KEYUTIL.getKey(privateKey);
			const hashAlg = 'sha256';
			let hSig = sign_rsa.signString(JSON.stringify(data), hashAlg);
			hSig = RSA.hex2b64(hSig); // hex 转 b64
			console.log('签名结果：', hSig);

			// 加密签名后的入参
			const parameter = {
				sign: hSig,
				data: cryptStr
			};
			console.log('加密后的用户登录参数：', parameter);
			resolve(parameter);
		});
	},

	/**
	 * 解密
	 * @param {string} data
	 * @param {string} privateKey
	 * @returns {string}
	 */
	decrypt(userData) {
		return new Promise((resolve, reject) => {
			let {
				data,
				sign
			} = userData;
			// 实例化rsa
			const rsa = new WxmpRsa();
			// 设置私钥
			rsa.setPrivateKey(privateKey);
			// 解密
			const decryptStr = rsa.decryptLong(data);
			console.log('解密后的结果：', decryptStr);
			// 验签
			let verify_rsa = new RSA.RSAKey();
			verify_rsa = RSA.KEYUTIL.getKey(publicKey);
			const signResult = RSA.b64tohex(sign);
			let verResult = verify_rsa.verifyString(decryptStr, signResult);
			if (!verResult) {
				console.log('验签失败');
				reject('验签失败');
			}
			
			try {
				resolve(JSON.parse(decryptStr));
			} catch {
				resolve(decryptStr);
			}
		})
	}
}